package com.nbjtjc.safe.filter;

import com.alibaba.fastjson.JSON;
import com.nbjtjc.safe.bean.Result;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录验证
 */
public class SessionFilter extends FormAuthenticationFilter {
    private static final Logger log = LoggerFactory.getLogger(SessionFilter.class);


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (this.isLoginRequest(request, response)) {
            if (this.isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return this.executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            if (log.isTraceEnabled()) {
                log.trace("Attempting to access a path which requires authentication.  Forwarding to the Authentication url [" + this.getLoginUrl() + "]");
            }
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            HttpServletRequest httpServletRequest= (HttpServletRequest) request;
            System.out.println(httpServletRequest.getHeader("Origin"));
            Result<String> result = new Result<>();
            result.setCode(100);
            result.setFalse("未登录或者过期");
            log.info("未登录或者过期");
            writer(JSON.toJSONString(result), httpServletResponse,httpServletRequest);
             return false;
        }
    }

    private void writer(String jsonStr, HttpServletResponse response,HttpServletRequest request) {
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "OPTIONS, GET, POST");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        //告诉浏览器编码方式
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.write(jsonStr);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
